package ca.uvic.cs.cogz.mapping.ui;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;

import javax.swing.JFrame;

public class NotificationFactory {
	private static NotificationFactory notificationManager;
	
	private Map<Integer, NotificationWindow> notificationWindows;
	
	private NotificationFactory() {
		notificationWindows = new TreeMap<Integer, NotificationWindow>(new Comparator<Integer>() {
			public int compare(Integer o1, Integer o2) {
				return o2.compareTo(o1);
			}
		});
	}

	public static NotificationFactory getInstance() {
		if(notificationManager == null) {
			notificationManager = new NotificationFactory();
		}
		
		return notificationManager;
	}
	
	public void displayNotification(JFrame parentFrame, String title, String message) {
		final NotificationWindow notificationWindow = new NotificationWindow(parentFrame, title, message);
		
		int locY = parentFrame.getHeight();
		int prevY = parentFrame.getHeight();
		for(Entry<Integer, NotificationWindow> notificationEntry : notificationWindows.entrySet()) {
			int y = notificationEntry.getKey();
			
			if(prevY - y >= 100) {
				break;
			}
			prevY -= 101;
		}
		locY = prevY;
		
		notificationWindows.put(locY, notificationWindow);
		notificationWindow.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosed(WindowEvent e) {
				notificationWindows.remove(notificationWindow.getStartLocY());
			}
		});
		
		notificationWindow.display(locY);
	}
}
